#!/usr/bin/python
import sys
import urllib2
import re
import json
from filmset import MyVideo
def fromFile():
    f = open('sh.m3u')
    line = f.readline()
    f.close()
    if len(line)>6:
        return line[5:].strip()
    else :
        return ''
def getJsonUrl(myVideo):
    data = urllib2.urlopen(myVideo.url,timeout=10).read();
    videoIds=re.findall('var[ ]+vid[ ]*=[ ]*[\"]([^\"]+)[\"]',data,re.I)
    if len(videoIds):
        return 'http://hot.vrs.sohu.com/vrs_flash.action?vid='+videoIds[0] 
    else:
        return ''
def jsonDone(myVideo,url):
    data = urllib2.urlopen(url,timeout=10).read(); 
    res = json.loads(data)
    allot = res['allot']
    prot = res['prot']
    myVideo.setNUrl(res['url'])
    myVideo.setName(res['data']['tvName'])
    for item in res['data']['clipsURL']:
        myVideo.addfile(item[22:]);
    for item in res['data']['su']:
        myVideo.addSu(item)
    return allot,prot
def getPlay(allot,prot,filep,sup):
    url = 'http://'+allot+'/?prot='+str(prot)+'&file='+filep+'&new='+sup 
    data = urllib2.urlopen(url,timeout=10).read()
    res = data.split('|')
    return res[0]+sup+'?key='+res[3]
# Script starts from here
if len(sys.argv) < 2:
    print 'No action specified.'
elif sys.argv[1].startswith('--'):
   option = sys.argv[1][2:]
   # fetch sys.argv[1] but without the first two characters
   if option == 'm3u' or option == 'rmvb' or option == 'update':
      if option == 'update':
          myVideo = MyVideo(fromFile())
      else:
          myVideo = MyVideo(sys.argv[2])
      jsonurl = getJsonUrl(myVideo)
      if len(jsonurl)>0:
          m_allot,m_prot = jsonDone(myVideo,jsonurl)
          for i in range(0,len(myVideo.files)):
              play = getPlay(m_allot,m_prot,myVideo.files[i],myVideo.sus[i])
              myVideo.addplayer(play)
          if option == 'rmvb':
              myVideo.download()
          else:
              myVideo.saveFile('sh.m3u')
   elif option == 'help':
      print '''This Application Version is 0.2
Options include:
--m3u <url> : make file from web url
--update    : self update m3u file
--rmvb <url>: download file from web url
--help      : Display this help'''
   else:
       print 'Unknown option.'
sys.exit();
